<?php

namespace app\common\model;

use app\lib\enum\Status;
use think\Exception;

class CmsArticle extends BaseModel
{
    //绑定资讯分类表
    public function bindCategory(){
        return $this->hasOne("CmsArticleCategory","acc_id","art_category_id");
    }


    //绑定机构表
    public function bindInstitution(){
        return $this->hasOne("PyInstitution","ins_id","art_institution_id");
    }

    //添加资讯
    public function articleAdd($data){
        if($data['art_category_id']==-1){
            return "请选择分类信息";
        }

        if(!is_numeric($data['art_sort'])){
            return "请输入整数排序";
        }

        //如果未填写过期时间，默认永不失效
        if($data['art_expire_time']==""){
            $data['art_expire_time']=config("setting.neverExpireTime");
        }else{
            $data['art_expire_time']=strtotime($data['art_expire_time']);
        }


        $data['art_create_time']=time();
        $isset=$this->where("art_title","=",$data['art_title'])
            ->where("art_institution_id","=",$data['art_institution_id'])
            ->find();
        if($isset){
            return "标题已存在";
        }

        $data=$this->dataFilter($data);
        try{
            $result=$this->insert($data);
        }catch (Exception $e){
            return "数据插入异常";
        }
        if(!$result){
            return "数据插入失败";
        }else{
            return 1;
        }
    }

    //编辑资讯
    public function articleEdit($data,$art_id){
        //判断在同一机构下，文章标题是否重复
        //查出未修改的数据，进行比较
        $articleInfo=$this->find($art_id);
        if($articleInfo['art_title']!=$data['art_title']&&$this->where("art_title","=",$data['art_title'])
                ->where("art_institution_id","=",$data['art_institution_id'])
                ->find()){
            return "该标题已存在";
        }

        //如果未填写过期时间，默认永不失效
        if($data['art_expire_time']==""){
            $data['art_expire_time']=config("setting.neverExpireTime");
        }else{
            $data['art_expire_time']=strtotime($data['art_expire_time']);
        }

        $data=$this->dataFilter($data);

        try{
            $result=$this->where("art_id","=",$art_id)->update($data);
        }catch (Exception $e){
            return "资讯编辑失败";
        }
        if(!$result){
            return "信息未发生变化";
        }else{
            return 1;
        }
    }

    //设置读取器，当图片不存在时，使用默认的图片
    public function getArtThumbAttr($value){
        if($value==""){
            $webInfo=cache("webInfo");
            return $webInfo['web_good_class_default_image'];
        }else{
            return $value;
        }
    }

}
